import { getAccount, setAccount, getToken, setToken, removeToken, getUser, setUser } from '@/utils/auth'
import { get, post } from '@/utils/http'
import { api } from '@/api'

const user = {
  state: {
    token: getToken(),
    account: getAccount(),
    user: getUser(),
    name: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account
    },
    SET_USER: (state, user) => {
      state.user = user
    }
  },

  actions: {
    // 登录
    Login({ commit }, user) {
      setToken(user.token)
      commit('SET_TOKEN', user.token)
      setUser(user)
      commit('SET_USER', user)
    },
    Remember({ commit }, account) {
      setAccount(account)
      commit('SET_ACCOUNT', account)
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        post(api.SYS_MENU).then(
          res => {
            if (res.data && res.data.length > 0) {
              commit('SET_ROLES', res.data)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
            // commit('SET_NAME', res.data.name)
            resolve(res.data)
          }
        )
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        get(api.SYS_LOGOUT).then(
          () => {
            commit('SET_ROLES', [])
            removeToken()
            resolve()
          }
        )
      })
    }
  }
}

export default user
